package cn.itcast;

import cn.itcast.pojo.ItemDoc;
import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.hmall.common.search.ItemClient;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

@SpringBootTest
public class HighLevelRestClient {

    @Autowired
    ItemClient client;

    private RestHighLevelClient clients;

    @Test
    public void findAll(){

        PageDTO<Item> list = client.list(1, 500);

        System.out.println(list);
    }

    @Test
    public void addData() throws IOException {
        long starTime = System.currentTimeMillis();

        // 从数据库拿数据
        for (int i = 100; i < 1000; i++) {
            PageDTO<Item> itemPageDTO = client.list(i, 100);

            Long total = itemPageDTO.getTotal();

            System.out.println(total);
            List<Item> itemList = itemPageDTO.getList();


            System.out.println(itemList);

            if (itemList.size() > 0) {
                BulkRequest request = new BulkRequest();
                for (Item item : itemList) {
                    ItemDoc itemDoc = new ItemDoc(item);
                    String jsonString = JSON.toJSONString(itemDoc);
                    // 创建添加文档的请求对象
                    IndexRequest request1 = new IndexRequest("item");
                    //把文档数据添加到请里
                    request1.id(String.valueOf(itemDoc.getId()));
                    request1.source(jsonString, XContentType.JSON);
                    // 往bulk请求中添加要添加的indexRequest对象
                    request.add(request1);
                }

                clients.bulk(request, RequestOptions.DEFAULT);
            }
        }

        long endTime = System.currentTimeMillis();

        System.out.println((endTime-starTime)/1000+"s");

    }

    @Test
    public void test1(){
        Item item = client.findItemById(100002465022l);


        System.out.println(item);
    }

    @BeforeEach
    void setUp() {
        clients = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.200.129:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        clients.close();
    }
}
